package com.dff.easy_excel_demo.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.dff.easy_excel_demo.entity.Student;
import com.dff.easy_excel_demo.service.HandleExcelService;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * create by: L.gy
 */
// 有个很重要的点 ExcelListener 不能被spring管理，
// 要每次读取excel都要new,然后里面用到spring可以构造方法传进去
public class ExcelListener<T> extends AnalysisEventListener<T> {

    /**
     * 每隔1000条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;

    private HandleExcelService handleExcelService;

    private List<Student> students = new ArrayList<>();

    public ExcelListener() {
    }

    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     */
    public ExcelListener(HandleExcelService handleExcelService) {
        this.handleExcelService = handleExcelService;
    }


    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        Integer currentRowNum = analysisContext.getCurrentRowNum();
        if (currentRowNum != 0){
            Student student = (Student) t;
            students.add(student);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        List<Student> list = new ArrayList<>();
        students.forEach(userReadModule -> {
            Student user = new Student();
            BeanUtils.copyProperties(userReadModule,user);
            list.add(user);
        });

        handleExcelService.saveBatch(list);
    }
}
